package com.whc.gulimall.product.exception;

import com.whc.common.exception.BizCodeEnume;
import com.whc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品异常统一处理类
 *
 * @author angaoen
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.whc.gulimall.product.controller")
public class ProductExceptionControllerAdvice {

    /**
     * JSR303校验异常统一处理方法
     *
     * @param e JSR303校验相关异常
     * @return 统一异常返回结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型{}", e.getMessage(), e.getClass());
        Map<String, String> resultMap = e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, DefaultMessageSourceResolvable::getDefaultMessage));
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg())
                .put("data", resultMap);
    }

}
